#Networking Class
import os
import socket
import fcntl
import struct
import sys

class Networking:
	def __init__(self,interface):
		self.Interface = interface
		self.SIOCGIFNETMASK = 0x891b
		self.SIOCGIFADDR = 0x8915
		
	def GetIPAddress(self):
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		return socket.inet_ntoa(fcntl.ioctl( s.fileno(),self.SIOCGIFADDR,struct.pack('256s', self.Interface[:15])
		)[20:24])
	
	def SetIpAdrees(self, IpAdress):
		GatewayActual = self.GetGateway()
		os.system("sudo ifconfig "+self.Interface+" "+IpAdress+" netmask "+self.GetNetMask())
		os.system("sudo route add default gw "+GatewayActual+" "+self.Interface)
		
			
	def GetNetMask(self):
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		netmask = fcntl.ioctl(s, self.SIOCGIFNETMASK, struct.pack('256s', self.Interface))[20:24]
		return socket.inet_ntoa(netmask)
	
	def SetNetMask(self, NetMask):
		GatewayActual = self.GetGateway()
		os.system("sudo ifconfig "+self.Interface+" "+self.GetIPAddress()+" netmask "+NetMask)
		os.system("sudo route add default gw "+GatewayActual+" "+self.Interface) 	
			
	
	def GetGateway(self):
			cmd = "ip route list dev "+ self.Interface + " | awk ' /^default/ {print $3}'"
			fin,fout = os.popen4(cmd)
			result = fout.read()
			return result
			
	def SetGateway(self, Gateway):
		os.system("sudo ifconfig "+self.Interface+" "+self.GetIPAddress()+" netmask "+self.GetNetMask()) 	
		os.system("sudo route del default gw "+self.GetGateway())
		os.system("sudo route add default gw "+Gateway +" "+self.Interface)
		
	
#Ejemplo de Implementacion

net = Networking("wlan0")
IP = net.GetIpAddress()
net.SetIpAddress("192.168.1.75")
